package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author kangchuang
 * 光纤止租方式联动0：自动止租，1手动止租
 */
@Service
public class StopRentStyleHandler extends AbstractAttrHandler {
    public static final String FIELDNAME = "ORD10111";

    public static final String ATTRVALUE = "0";

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneCommonService operateSceneCommonService;

    @Override
    public void init(CommonAttrVO commonAttrVO) {
        String postProvinceNbr = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        if (KiteStringUtils.equals(LocalKeyConsts.PROVINCE_SHANGHAI, postProvinceNbr) && KiteStringUtils.isBlank(commonAttrVO.getOriginValue())) {
            // 上海五大双线 停机、预销户/销户时的止租：默认“自动止租”，止租时间以页面录入的止租时间为准，可修改
            commonAttrVO.setValue(ATTRVALUE);
            String commonDesc = Optional.ofNullable(AttrValueCache.getAttrValue(commonAttrVO.getAttrId(), commonAttrVO.getValue()))
                .map(AttrValue::getAttrValueName).orElse(commonAttrVO.getValue());
            commonAttrVO.setValueDesc(commonDesc);
            commonAttrVO.setDefaultValue(ATTRVALUE);
            setCommonAttr(commonAttrVO);
        }
    }

    @Override
    public DataResult<Boolean> apply (String sceneInstId, String fieldName, String value, String valueDesc) {
        if (FIELDNAME.equalsIgnoreCase(fieldName) && ATTRVALUE.equals(value)) {
            KiteAttr attr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10123");
            attr.setShowType("D");
            operateSceneCommonService.setCommonAttr(sceneInstId, attr);
        } else {
            KiteAttr attr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10123");
            attr.setShowType("E");
            operateSceneCommonService.setCommonAttr(sceneInstId, attr);
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }
}
